package com.reger.l2cache.pipeline.pipe;

import org.springframework.core.serializer.support.SerializationFailedException;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.reger.l2cache.pipeline.core.PipelineCore;

public class JackjsonRedisPipeline<T> extends RedisPipeline<String, String, T> {

	RedisSerializer<T> JackjsonRedisSerializer = new RedisSerializer<T>() {
		ObjectMapper objectMapper = new ObjectMapper();
		{
			objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
		}

		@Override
		public byte[] serialize(T t) throws SerializationException {
			try {
				return objectMapper.writeValueAsBytes(t);
			} catch (JsonProcessingException e) {
				throw new SerializationFailedException("序列化失败", e);
			}
		}

		@Override
		@SuppressWarnings("unchecked")
		public T deserialize(byte[] bytes) throws SerializationException {
			return (T) stringSerializer.deserialize(bytes);
		}
	};

	@SuppressWarnings("unchecked")
	public JackjsonRedisPipeline(PipelineCore pipelineCore) {
		super(pipelineCore);
		this.setKeySerializer(stringSerializer);
		this.setHashKeySerializer(stringSerializer);
		this.setValueSerializer(JackjsonRedisSerializer);
	}
}
